package com.lgc.javathread.threadPoolTest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Callable+Future/FutureTask却可以获取多线程运行的结果，可以在等待时间太长没获取到需要的数据的情况下取消该线程的任务
 */
public class ThreadPoolProgram2 {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool= Executors.newFixedThreadPool(5);
        List<Future<String>> futureList =new ArrayList<>();
        List<Future<Integer>> futureList1 =new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            MyCallable myCall = new MyCallable(i);
            //Future<String> result = cachedThreadPool.submit(myCall);
            Future<String> result = cachedThreadPool.submit(myCall);

            futureList.add(result);
        }

        System.out.println("isShutdown "+cachedThreadPool.isShutdown());
        System.out.println("isTerminated "+cachedThreadPool.isTerminated());
        cachedThreadPool.shutdown();
        System.out.println("isShutdown "+cachedThreadPool.isShutdown());

        try {
            cachedThreadPool.awaitTermination(1,TimeUnit.SECONDS); //等1秒后继续，不管线程池是否结束
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            while (true)
            {
                if(cachedThreadPool.isTerminated())
                {
                    System.out.println("所有的子线程都结束了！");
                    break;
                }
                else {
                    System.out.println("执行中！");
                }
                Thread.sleep(500);
            }

            for (Future item:
                    futureList) {
                System.out.println(item.get());
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
